package com.gexiaobao.pigeon.ui.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.CountDownTimer
import android.os.Handler
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.DataBindBaseViewHolder
import com.gexiaobao.pigeon.app.model.bean.ShopOrderListResponse
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.databinding.ItemShopOrderBinding
import java.math.BigDecimal
import java.util.Date


/**
 * @author: hxw
 * @date  : 2023/2/2
 * @desc  :
 */
class ShopOrderListAdapter(data: ArrayList<ShopOrderListResponse.ListBean>, private var systemDate: Date) :
    BaseQuickAdapter<ShopOrderListResponse.ListBean, DataBindBaseViewHolder>(R.layout.item_shop_order, data) {

    private var mOnItemClickListener: OnChildItemClickListener? = null

    private val timeMap = HashMap<AppCompatTextView, MyCountDownTimer>()
    private val handler = Handler()
    private val runnable = object : Runnable {
        override fun run() {
            systemDate.time = systemDate.time + 1000
            handler.postDelayed(this, 1000)
        }
    }

    init {
        handler.postDelayed(runnable, 1000)
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun convert(holder: DataBindBaseViewHolder, item: ShopOrderListResponse.ListBean) {
        val binding = DataBindBaseViewHolder.getBinding(holder) as ItemShopOrderBinding
        binding.data = item
        binding.executePendingBindings()//防止列表抖动

        val tvProductOutBound = holder.getView<AppCompatTextView>(R.id.tvProductOutBound)
        val llItemWaitPay = holder.getView<LinearLayout>(R.id.llItemWaitPay)
        val tvItemPriceTotal = holder.getView<AppCompatTextView>(R.id.tvItemPriceTotal)
        val shopOrderDetailStatus = holder.getView<AppCompatTextView>(R.id.shop_order_detail_status)

        llItemWaitPay.background.alpha = 100

        if (!item.isEmpty() && item.list.size == 1) {
            shopOrderDetailStatus.text = item.list[0].shopName
            holder.setGone(R.id.shop_order_detail_status_more, false)
        } else {
            shopOrderDetailStatus.text = context.getString(R.string.pigeon_baby)
            holder.setGone(R.id.shop_order_detail_status_more, true)
        }

        when (item.orderStatus) {
            0, 1 -> {
                holder.setGone(R.id.llItemWaitPay, false)
                holder.setText(R.id.tvItemDelOrder, context.getString(R.string.activity_market_shop_order_payfor_delete))//"取消订单"
                holder.setText(R.id.tvItemToPay, context.getString(R.string.activity_market_shop_order_payfor_pay))//"去付款"
                holder.setGone(R.id.tvItemToPay, false)
            }

            9 -> {
                holder.setGone(R.id.llItemWaitPay, true)
                holder.setText(R.id.tvItemDelOrder, context.getString(R.string.Delete_order))//"删除订单"
                holder.setText(R.id.tvItemToPay, context.getString(R.string.buy_again))//"再次购买"
                holder.setGone(R.id.tvItemToPay, true)
            }
        }

        holder.itemView.apply {
            binding.itemRecyclerView.adapter = null
            if (item.isEmpty() || item.list.size == 0) {
                holder.setGone(R.id.itemRecyclerView, true)
                return
            }
            holder.setGone(R.id.itemRecyclerView, false)
            val mAdapterGoods = GoodsItemAdapter(item.list, item)
            binding.itemRecyclerView.apply {
                layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
                adapter = mAdapterGoods
                mAdapterGoods.notifyDataSetChanged()
            }

            mAdapterGoods.setOnChildGoodsItemClickListener(object : GoodsItemAdapter.OnChildItemGoodsClickListener {
                override fun onChildItemGoodsClick(position: Int) {
                    mOnItemClickListener?.onChildItemClick(holder.layoutPosition)
                }
            })
        }

        if (!item.isEmpty() && item.list.size != 0) {
            var totalPrice = BigDecimal("0.00")
            item.list.forEachIndexed { _, listType ->
                if (listType.list.isNotEmpty()) {
                    listType.list.forEachIndexed { _, listGoods ->
                        val price = BigDecimal(listGoods.salePrice.toString())
                        val count = BigDecimal(listGoods.amount.toString())
                        val result = price.multiply(count)
                        totalPrice = totalPrice.add(result)
                    }
                }
            }
            SettingUtil.setPrice(totalPrice.toString(), tvItemPriceTotal, 50, Color.BLACK)
        }

        var tc: MyCountDownTimer? = timeMap[tvProductOutBound]
        if (tc != null) {
            tc.cancel()
            tc = null
        }
        /** 获取倒计时时间 */
        val time = item.closeSecond * 1000

        /** 创建倒计时，与控件绑定 */
        val cdu = MyCountDownTimer(holder.layoutPosition, time, 1000, tvProductOutBound)
        cdu.start()
        /** 【醒目】此处需要map集合将控件和倒计时类关联起来 */
        timeMap[tvProductOutBound] = cdu
    }

    /**
     * 退出时清空所有item的计时器
     */
    fun cancelAllTimers() {
        val s: MutableSet<MutableMap.MutableEntry<AppCompatTextView, MyCountDownTimer>> = timeMap.entries
        val it = s.iterator()
        while (it.hasNext()) {
            try {
                val pairs = it.next() as MutableMap.MutableEntry<*, *>
                var cdt: MyCountDownTimer? = pairs.value as MyCountDownTimer
                cdt!!.cancel()
                cdt = null
            } catch (e: Exception) {
            }
        }
        timeMap.clear()
    }

    private fun removeTimer() {
        handler.removeCallbacks(runnable)
    }

    fun reSetTimer(date: Date) {
        removeTimer()
        systemDate = date
        handler.postDelayed(runnable, 1000)
    }

    fun setOnChildGoodsClickListener(listener: OnChildItemClickListener?) {
        mOnItemClickListener = listener
    }

    interface OnChildItemClickListener {
        fun onChildItemClick(position: Int)
    }

    /**
     * 倒计时类，每间隔countDownInterval时间调用一次onTick()
     * index参数可去除，在这里只是为了打印log查看倒计时是否运行
     */
    private inner class MyCountDownTimer(
        var index: Int, millisInFuture: Long,
        var countDownInterval: Long,
        var tv: AppCompatTextView
    ) : CountDownTimer(millisInFuture, countDownInterval) {
        @SuppressLint("SetTextI18n")
        override fun onTick(millisUntilFinished: Long) {
            /** millisUntilFinished为剩余时间长 */
//            LogUtils.debugInfo("xujf", "====倒计时还活着===第 $index 项item======")
//            /** 设置时间格式 */
//            val m = millisUntilFinished / countDownInterval
//            val hour = m / (60 * 60)
//            val minute = (m / 60) % 60
//            val s = m % 60
            tv.text = DatetimeUtil.formatDateTime(millisUntilFinished / 1000)
        }

        override fun onFinish() {
            // 可以做一些刷新动作
        }
    }
}